package com.leyou.order.service;

import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.client.ItemClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.dto.SkuDTO;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.entity.Order;
import com.leyou.order.entity.OrderDetail;
import com.leyou.order.entity.OrderLogistics;
import com.leyou.order.enums.OrderStatusEnum;
import com.leyou.order.interceptors.UserInterceptor;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.utils.PayHelper;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrderService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper detailMapper;
    @Autowired
    private OrderLogisticsMapper logisticsMapper;
    @Autowired
    private UserClient userClient;
    @Transactional
    public Long createOrder(@Valid OrderDTO orderDTO) {

        Order order = new Order();

        long orderId = idWorker.nextId();
        order.setOrderId(orderId);

        Long userId = UserInterceptor.getUser().getId();
        order.setUserId(userId);

        //List<CartDTO> carts = orderDTO.getCarts();
        @NotNull List<CartDTO> carts = orderDTO.getCarts();

        List<Long> idList = carts.stream().map(CartDTO::getSkuId).collect(Collectors.toList());
        Map<Long, Integer> cartMap = carts.stream().collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum));

        List<SkuDTO> skuList = itemClient.querySkuByIds(idList);

        List<OrderDetail> details = new ArrayList<>();
        long total=0;
        for(SkuDTO sku:skuList){
            Integer num = cartMap.get(sku.getId());
            total +=sku.getPrice()*num;
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(orderId);
            detail.setImage(StringUtils.substringBefore(sku.getImages(),","));
            detail.setNum(num);
            detail.setSkuId(sku.getId());
            detail.setOwnSpec(sku.getOwnSpec());
            detail.setPrice(sku.getPrice());
            detail.setTitle(sku.getTitle());

            details.add(detail);
        }
        order.setPostFee(0L);
        order.setTotalFee(total);
        @NotNull Integer paymentType = orderDTO.getPaymentType();
        order.setPaymentType(paymentType);
        order.setActualFee(total+order.getPostFee());

        order.setStatus(OrderStatusEnum.INIT.value());

        int count = orderMapper.insertSelective(order);
        if(count!= 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        count = detailMapper.insertDetailList(details);
        if(count!=details.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        @NotNull Long addressId = orderDTO.getAddressId();
        AddressDTO addr = userClient.queryAddressById(userId,addressId );

        OrderLogistics logistics = BeanHelper.copyProperties(addr, OrderLogistics.class);
        logistics.setOrderId(orderId);

        count = logisticsMapper.insertSelective(logistics);
        if(count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        itemClient.minusStock(cartMap);

        return orderId;
    }

    public Order queryOrderById(Long orderId) {
        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        if(null==order){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return order;
    }

    @Autowired
    private PayHelper payHelper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String createPayUrl(Long orderId) {
        String key="ly.pay.url."+orderId;
        String cacheUrl = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(cacheUrl)){
            return cacheUrl;
        }

        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        if(null==order){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }

        Integer status = order.getStatus();
        if(!status.equals(OrderStatusEnum.INIT.value())){
            throw new LyException(ExceptionEnum.INVALID_ORDER_STATUS);
        }

        String url = payHelper.createOrder(orderId, 1L, "乐优商城商品");

        redisTemplate.opsForValue().set(key,url,2, TimeUnit.HOURS);

        return url;
    }

    @Transactional
    public void handleNotify(Map<String, String> result) {
        // 1 签名校验
        try {
            payHelper.isValidSign(result);
        }catch (Exception e){
            log.error("【微信回调】微信签名有误！, result: {}",result, e);
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_SIGN, e);
        }
        // 2、业务校验
        payHelper.checkResultCode(result);

        // 3 校验金额数据
        String totalFeeStr = result.get("total_fee");
        String tradeNo = result.get("out_trade_no");
        if(StringUtils.isEmpty(totalFeeStr) || StringUtils.isEmpty(tradeNo)){
            // 回调参数中必须包含订单编号和订单金额
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_PARAM);
        }
        // 3.1 获取结果中的金额
        long totalFee = Long.valueOf(totalFeeStr);
        // 3.2 获取订单
        Long orderId = Long.valueOf(tradeNo);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        // 3.3.判断订单的状态，保证幂等
        if(!order.getStatus().equals(OrderStatusEnum.INIT.value())){
            // 订单已经支付，返回成功
            return;
        }
        // 3.4.判断金额是否一致
        if(totalFee != /*order.getActualPay()*/ 1){
            // 金额不符
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_PARAM);
        }

        // 4 修改订单状态
        Order orderStatus = new Order();
        orderStatus.setStatus(OrderStatusEnum.PAY_UP.value());
        orderStatus.setOrderId(orderId);
        orderStatus.setPayTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(orderStatus);
        if(count != 1){
            log.error("【微信回调】更新订单状态失败，订单id：{}", orderId);
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        log.info("【微信回调】, 订单支付成功! 订单编号:{}", orderId);
    }

    public Integer queryStatusById(Long orderId) {
        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        if(null==order){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return order.getStatus();
    }
}
